<script setup>
import { ref, computed, getCurrentInstance, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();

// 表格数据
const tableData = ref([]);

// 场景列表
const sceneList = ref([]);

// 仿真数据列表
const simulationDataList = ref([]);

// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10);

const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 表单数据
const formData = ref({
  id: "",
  name: "",
  sceneId: "",
  sceneName: "",
  simulationDataId: "",
  simulationDataName: "",
  description: "",
});

// 弹框相关状态
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref(null);

// 表单验证规则
const formRules = ref({
  name: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  sceneName: [{ required: true, message: "请选择场景名称", trigger: "change" }],
  simulationDataId: [
    { required: true, message: "请输入仿真数据ID", trigger: "blur" },
  ],
});

// 获取数据
const getSampleList = async () => {
  try {
    const data = await proxy.$api.getSampleList();
    tableData.value = data;
  } catch (error) {
    ElMessage.error("获取数据失败：" + error.message);
  }
};

// 获取场景列表
const getSceneList = async () => {
  try {
    const data = await proxy.$api.getSceneList();
    sceneList.value = data;
  } catch (error) {
    ElMessage.error("获取场景列表失败：" + error.message);
  }
};

// 获取仿真数据列表
const getSimulationDataList = async () => {
  try {
    const data = await proxy.$api.getSimulationdatasList();
    simulationDataList.value = data || [];
  } catch (error) {
    ElMessage.error("获取仿真数据失败：" + error.message);
  }
};

// 新增数据
const handleAdd = () => {
  dialogTitle.value = "新增数据";
  formData.value = {
    id: "",
    name: "",
    sceneId: "",
    sceneName: "",
    simulationDataId: "",
    simulationDataName: "",
    description: "",
  };
  dialogVisible.value = true;
};

// 编辑数据
const handleEdit = (row) => {
  dialogTitle.value = "编辑数据";
  formData.value = { ...row };
  dialogVisible.value = true;
};

// 监听场景名称选择变化
const handleSceneChange = (val) => {
  const selected = sceneList.value.find((item) => item.name === val);
  if (selected) {
    formData.value.sceneId = Number(selected.id);
  } else {
    formData.value.sceneId = "";
  }
};

// 监听仿真数据名称选择变化
const handleSimulationDataChange = (val) => {
  const selected = simulationDataList.value.find((item) => item.name === val);
  if (selected) {
    formData.value.simulationDataId = Number(selected.id);
  } else {
    formData.value.simulationDataId = "";
  }
};

// 删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认要删除 "${row.name}" 这条数据吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await proxy.$api.deleteSample(row.id);
        ElMessage.success("删除成功");
        getSampleList();
      } catch (error) {
        ElMessage.error("删除失败: " + error.message);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    // 保证sceneId和sceneName同步
    const selectedScene = sceneList.value.find(
      (item) => item.name === formData.value.sceneName
    );
    if (selectedScene) {
      formData.value.sceneId = Number(selectedScene.id);
    }
    // 保证simulationDataId和simulationDataName同步
    const selectedSim = simulationDataList.value.find(
      (item) => item.name === formData.value.simulationDataName
    );
    if (selectedSim) {
      formData.value.simulationDataId = Number(selectedSim.id);
    }
    if (formData.value.id) {
      await proxy.$api.updateSample(formData.value);
      ElMessage.success("更新成功");
    } else {
      await proxy.$api.addSample(formData.value);
      ElMessage.success("新增成功");
    }
    dialogVisible.value = false;
    getSampleList();
  } catch (error) {
    if (!error.message) return;
    ElMessage.error("操作失败: " + error.message);
  }
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

onMounted(() => {
  getSampleList();
  getSceneList();
  getSimulationDataList();
});
</script>

<template>
  <div class="app-container">
    <!-- 操作按钮 -->
    <div class="mb-4">
      <el-button type="primary" @click="handleAdd">
        <el-icon><plus /></el-icon>
        新增
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="currentPageData" style="width: 100%" border stripe>
      <!-- ID 列 -->
      <el-table-column prop="id" label="ID" width="80" align="center" />

      <!-- 名称列 -->
      <el-table-column
        prop="name"
        label="名称"
        align="center"
        min-width="120"
      />

      <!-- 场景ID列 -->
      <el-table-column
        prop="sceneId"
        label="场景ID"
        align="center"
        width="120"
      />

      <!-- 场景名称列 -->
      <el-table-column
        prop="sceneName"
        label="场景名称"
        align="center"
        min-width="120"
      />

      <!-- 仿真数据ID列 -->
      <el-table-column
        prop="simulationDataId"
        label="仿真数据ID"
        align="center"
        width="140"
      />

      <!-- 仿真数据名称列 -->
      <el-table-column
        prop="simulationDataName"
        label="仿真数据名称"
        align="center"
        min-width="150"
      />

      <!-- 描述列 -->
      <el-table-column
        prop="description"
        label="描述"
        align="center"
        min-width="180"
        show-overflow-tooltip
      />

      <!-- 操作列 -->
      <el-table-column fixed="right" label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      :total="tableData.length"
    />

    <!-- 新增/编辑弹框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="场景名称" prop="sceneName">
          <el-select
            v-model="formData.sceneName"
            placeholder="请选择场景名称"
            filterable
            @change="handleSceneChange"
          >
            <el-option
              v-for="item in sceneList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="场景ID">
          <el-input
            v-model="formData.sceneId"
            placeholder="请选择场景名称"
            readonly
          />
        </el-form-item>

        <el-form-item label="仿真数据名称" prop="simulationDataName">
          <el-select
            v-model="formData.simulationDataName"
            placeholder="请选择仿真数据名称"
            filterable
            @change="handleSimulationDataChange"
          >
            <el-option
              v-for="item in simulationDataList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仿真数据ID">
          <el-input
            v-model="formData.simulationDataId"
            placeholder="请选择仿真数据名称"
            readonly
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.app-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 1rem;
}

.el-table {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
